<template>
  <div class="batch-download">
    <div class="singer-img" ref="singerImg">hello</div>
    <div class="singer-img-plus" ref="singerImgPlus"></div>
    <el-button @click="downloadDOM">下载 DOM 节点</el-button>
    <el-button @click="downloadZipTxt">下载 zip 压缩包</el-button>
    <el-button @click="downloadZipImg">下载 图片 压缩包</el-button>
    <el-button @click="downloadZip">下载 图片(两张相同的) 压缩包</el-button>
    <el-button @click="downloadZipPlus">下载 图片(多张不同的) 压缩包</el-button>
  </div>
</template>

<script setup>
import html2canvas from "html2canvas"
import FileSaver from 'file-saver'
import JSZip from 'jszip'

const singerImg = ref()
const singerImgPlus = ref()
const downloadDOM = async () => {
  // dom节点 =》 转换为canvas对象 =》 转换为blob对象 =》 通过FileSaver库下载blob对象
  const canvas = await html2canvas(singerImg.value)
  canvas.toBlob(blob => {
    FileSaver(blob, 'example.png')
  })
}
const downloadZipTxt = async () => {
  const zip = new JSZip()
  zip.file('hello.txt', 'hello')
  const blob = await zip.generateAsync({ type: 'blob' })
  FileSaver(blob, 'example.zip')
}
const downloadZipImg = async () => {
  const canvas = await html2canvas(singerImg.value)
  canvas.toBlob(async blob => {
    const zip = new JSZip()
    zip.file('example.png', blob)
    const content = await zip.generateAsync({ type: 'blob' })
    FileSaver(content, 'example.zip')
  })
}
const toBlobPromise = promise => new Promise(async resolve => {
  const zip = new JSZip()
  const list = await Promise.all(promise)
  list.forEach((item, index) => {
    // 碰到这种回调，不知道什么时候执行完的，用一个 Promise 中的 resolve() 就可以了
    item.toBlob(blob => {
      zip.file(`example${index}.png`, blob)
      if (index === list.length - 1) resolve(zip)
    })
  })
})
const downloadZip = async () => {
  const promise = [await html2canvas(singerImg.value), await html2canvas(singerImg.value)]
  const zip = await toBlobPromise(promise)
  const content = await zip.generateAsync({ type: 'blob' })
  FileSaver(content, 'example.zip')
}
const downloadZipPlus = () => {

}
</script>

<style scoped lang="scss">

</style>
